<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="角色名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入角色名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="权限标识" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入权限标识"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="角色状态" clearable>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb-10">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="角色ID" align="center" prop="id" />
      <el-table-column label="角色名称" align="center" prop="roleName" :show-overflow-tooltip="true" />
      <el-table-column label="权限标识" align="center" prop="roleCode" :show-overflow-tooltip="true" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="scope.row.status === '0' ? 'danger' : 'success'">
            {{ scope.row.status === '0' ? '停用' : '正常' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            type="text"
            @click="handlePermission(scope.row)"
          >分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页区域 -->
    <el-pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="roleForm" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="roleCode">
          <el-input v-model="form.roleCode" placeholder="请输入权限标识" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in statusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" v-model="openPermission" width="600px" append-to-body>
      <el-form :model="permissionForm" label-width="80px">
        <el-form-item label="角色名称">
          <el-input v-model="permissionForm.name" disabled />
        </el-form-item>
        <el-form-item label="权限标识">
          <el-input v-model="permissionForm.code" disabled />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            ref="menuTreeRef"
            :data="menuOptions"
            :props="{ label: 'title', children: 'children' }"
            show-checkbox
            node-key="id"
            empty-text="加载中，请稍候"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPermissionForm">确 定</el-button>
          <el-button @click="cancelPermission">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listRole, getRole, delRole, addRole, updateRole, assignRoleMenu } from '@/api/system/role'
import { treeMenu, getRoleMenus } from '@/api/system/menu'

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 总条数
const total = ref(0)
// 角色表格数据
const roleList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否显示权限弹出层
const openPermission = ref(false)
// 菜单树选项
const menuOptions = ref([])
// 表单参考
const roleForm = ref(null)
const menuTreeRef = ref(null)

// 状态数据字典
const statusOptions = [
  { value: '0', label: '停用' },
  { value: '1', label: '正常' }
]

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  code: undefined,
  status: undefined
})

// 表单参数
const form = reactive({
  id: undefined,
  roleName: undefined,
  roleCode: undefined,
  description: '',
  status: '1',
  remark: undefined
})

// 权限表单参数
const permissionForm = reactive({
  roleId: undefined,
  name: undefined,
  code: undefined,
  menuIds: []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '角色名称不能为空', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '权限标识不能为空', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '显示顺序不能为空', trigger: 'blur' }
  ]
}

// 获取角色列表
const getList = () => {
  loading.value = true
  listRole(queryParams).then(response => {
    roleList.value = response.data.records
    total.value = response.data.total
    loading.value = false
  })
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 取消权限按钮
const cancelPermission = () => {
  openPermission.value = false
  permissionForm.roleId = undefined
  permissionForm.name = undefined
  permissionForm.code = undefined
  permissionForm.menuIds = []
}

// 表单重置
const reset = () => {
  form.id = undefined
  form.name = undefined
  form.code = undefined
  form.sort = 0
  form.status = '1'
  form.remark = undefined
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.name = undefined
  queryParams.code = undefined
  queryParams.status = undefined
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加角色'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const roleId = row.id || ids.value[0]
  getRole(roleId).then(response => {
    Object.assign(form, response.data)
    open.value = true
    title.value = '修改角色'
  })
}

// 提交按钮
const submitForm = () => {
  roleForm.value.validate(valid => {
    if (valid) {
      if (form.id !== undefined) {
        updateRole(form).then(response => {
          ElMessage.success('修改成功')
          open.value = false
          getList()
        })
      } else {
        addRole(form).then(response => {
          ElMessage.success('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

// 删除按钮操作
const handleDelete = (row) => {
  const roleIds = row.id || ids.value
  ElMessageBox.confirm('是否确认删除角色编号为"' + roleIds + '"的数据项?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delRole(roleIds)
  }).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

// 分配权限操作
const handlePermission = async (row) => {
  permissionForm.roleId = row.id
  permissionForm.name = row.name
  permissionForm.code = row.code
  
  // 获取菜单树
  const menuRes = await treeMenu()
  menuOptions.value = menuRes.data
  
  // 获取角色菜单
  const roleMenuRes = await getRoleMenus(row.id)
  permissionForm.menuIds = roleMenuRes.data || []
  
  openPermission.value = true
  
  // 等待DOM更新后设置选中节点
  setTimeout(() => {
    menuTreeRef.value.setCheckedKeys(permissionForm.menuIds)
  }, 100)
}

// 提交权限表单
const submitPermissionForm = () => {
  const menuIds = menuTreeRef.value.getCheckedKeys()
  assignRoleMenu(permissionForm.roleId, menuIds).then(response => {
    ElMessage.success('修改成功')
    openPermission.value = false
  })
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}
</style>